﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace PhotovoltaicETL
{
    public partial class ETLService : ServiceBase
    {
        /// <summary>
        /// 每次计时对于整时偏移毫秒数，用于错开误差或其他整点计算时导致的数据不一致或错误
        /// </summary>
        const int startAddMillisecond = 100;
        /// <summary>
        /// 1分钟定时器。每分钟检查一次是否需要计算
        /// </summary>
        System.Timers.Timer tm = new System.Timers.Timer();
        /// <summary>
        /// ETL单例
        /// </summary>
        DataETL contex = DataETL.Context;
        /// <summary>
        /// 服务构造函数
        /// </summary>
        public ETLService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 服务启动函数
        /// </summary>
        /// <param name="args">服务启动时传入参数</param>
        protected override void OnStart(string[] args)
        {
            tm.Elapsed += Tm_Elapsed;
            tm.Interval = 60000 - DateTime.UtcNow.Second * 1000 - DateTime.UtcNow.Millisecond
                + startAddMillisecond;
            tm.Start();
        }

        /// <summary>
        /// 1分钟定时器定时处理任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //if(tm.Interval != 60000)
            tm.Interval = 60000 - DateTime.UtcNow.Second * 1000 - DateTime.UtcNow.Millisecond
                + startAddMillisecond;
            try
            {
                contex.DoETL();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
        /// <summary>
        /// 服务停止时用于释放资源
        /// </summary>
        protected override void OnStop()
        {
            tm.Stop();
            tm.Dispose();
        }
    }
}
